package com.moon.controller;

import com.moon.utils.BaseController;
import com.moon.ws.WsHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/p")
public class PushController extends BaseController {
    @RequestMapping("/bkTime")
    @ResponseBody
    public String bkTime() {
        Date d = new Date();
        String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d);
        return s;
    }

    @RequestMapping("/send")
    @ResponseBody
    public String send(String info, HttpServletRequest req) {
        super.saveToAppList(req, String.class, "chatlist", info, 200);
        return "success";
    }

    @RequestMapping("/receive")
    @ResponseBody
    public List<String> receive(HttpServletRequest req) {
        return super.getAppList(req, String.class, "chatlist");
    }

    @RequestMapping("/random")
    @ResponseBody
    public String random() throws InterruptedException {
        while (true) {
            Random r = new Random();
            int num = r.nextInt(9000) + 1000;
            System.out.println("num : " + num);
            if (num >= 8000) {
                return num + "";
            }
            Thread.sleep(1200);
        }
    }


    @Autowired
    WsHandler wsHandler;

    //@Scheduled(fixedDelay = 10000)
    public void pushToAll() throws IOException {
        Map<String, WebSocketSession> clients = wsHandler.getClients();
        for (Map.Entry<String, WebSocketSession> et : clients.entrySet()) {
            TextMessage textMessage = new TextMessage("你好，我是月亮一族。");
            et.getValue().sendMessage(textMessage);
        }
    }

}
